package com.matrix.admin.open.test.service.impl;

import com.martix.util.SettingUtil;
import com.matrix.admin.open.test.service.IUtilsTestService;
import com.matrix.common.utils.MaIdUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liuweizhong
 * @since 2024-02-11
 */
@Slf4j
@Service
public class UtilsTestServiceImpl implements IUtilsTestService {
    @Resource
    private MaIdUtil maIdUtil;

    @Override
    public String testNewId() {
        log.info("============[开始测试id生成]============");
//        int loops = 10000000;
        int loops = 100;
        int threadCount = 8;
        Map<Integer, List<String>> results = new ConcurrentHashMap<>();
        for (int i = 0; i < threadCount; i++) {
            final int finalI = i;
            Thread.ofVirtual().start(() -> {
                for (int j = 1; j <= loops; j++) {
                    List<String> strings = results.get(finalI);
                    if (strings == null) {
                        strings = new ArrayList<>();
                        strings.add(maIdUtil.newIdStr());
                        results.put(finalI, strings);
                    } else {
                        strings.add(maIdUtil.newIdStr());
                    }
                    if (j % 5000 == 0) {
                        log.info("线程 {} 已生成{}个ID", finalI, j);
                    }
                }
                log.info("==============线程 {} 运行结束", finalI);
            });
        }

        boolean b = testSuccess(results, threadCount, loops);
        if (b) {
            log.info("============[校验完成]============");
        }

        List<String> totalList = new ArrayList<>();
        for (int i = 0; i < threadCount; i++) {
            List<String> strings = results.get(i);
            totalList.addAll(strings);
        }
        HashSet<String> set = new HashSet<>(totalList);
        log.info("===========生成的ID数量：{}，重复的ID数量：{}", set.size(), totalList.size() - set.size());

        log.info("================[结束测试]=================");
        return maIdUtil.newIdStr();
    }

    private boolean testSuccess(Map<Integer, List<String>> results, int threadCount, int loops) {
        try {
            log.info("============> [主线程休眠一次]");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < threadCount; i++) {
            List<String> strings = results.get(i);
            if (strings == null || strings.size() < loops) {
                if (strings == null) {
                    log.error("线程 {} 生成的ID数量为null", i);
                } else {
                    log.error("线程 {} 生成的ID数量{}个", i, strings.size());
                }
                testSuccess(results, threadCount, loops);
            }
        }
        return true;
    }

    private List<String> generateIds(int count) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            list.add(maIdUtil.newIdStr());
        }
        return list;
    }

    @Override
    public String testSetting() {
        log.info("================[开始测试]=================");
        long l = System.currentTimeMillis();
        // 使用默认的配置文件路径
        String settingByKey = SettingUtil.getInstance().getSettingByKey("anothersetting");
        long l1 = System.currentTimeMillis();
        log.info("获取配置耗时：{}ms, 配置值：{}", l1 - l, settingByKey);

        long l2 = System.currentTimeMillis();
        Map<String, String> settingMap = SettingUtil.getInstance().getSettingMap(List.of("# 这是一个注释", "anothersetting", "setting1112"));
        log.info("获取配置map耗时：{}ms, 配置map：{}", System.currentTimeMillis() - l2, settingMap);
        return maIdUtil.newIdStr();
    }


    @Override
    public String test() {


        return maIdUtil.newIdStr();
    }

}
